package com.yh.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.pojo.Product;
import com.yh.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    ProductService productService;

    /**
     * 这里的查询所有，包含了分页;
     * @return
     */
    @GetMapping("findAll")
    public String findAll(@RequestParam(name = "page",defaultValue = "1") Integer page,
                          @RequestParam(name = "size",defaultValue = "5") Integer size, Model model){
        //分页的设置，放在第一条语句;
        PageHelper.startPage(page,size);
        List<Product> productList = productService.findAll();
        //分页类设置
        PageInfo<Product>pageInfo=new PageInfo<>(productList);
        //放到model，传递数据;
        model.addAttribute("pageInfo",pageInfo);
        return "product-list";
    }

    /**
     * 2.1 增加之前，跳转到添加产品页面
     * @return
     */
    @GetMapping("product-add")
    public String toadd(){
        return "product-add";
    }

    /**
     * 2.2 新增操作
     * @param product
     * @return
     */
    @PostMapping("save")
    public String save(Product product){
        productService.save(product);
        return "redirect:/product/findAll";
    }

    /**
     * 3.查看产品详情信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("findById")
    public String getProduct(Integer id,Model model){
        Product product = productService.findById(id);
        model.addAttribute("product",product);
        return "product-show";
    }
    @PostMapping("edit")
    public String update(Product product){
        productService.update(product);
        return "redirect:/product/findAll";
    }
    @GetMapping("editById")
    public String editById(Integer id, Model model) {
        Product product = productService.findById(id);
        model.addAttribute("product", product);
        return "product-edit";
    }
    @RequestMapping("deleteById")
    public String delete(Integer id) {
        productService.delete(id);
        return "redirect:/product/findAll";
    }

    @RequestMapping("selectDelete")
    public String selectDelete(Integer[] ids) {
        for (Integer id : ids) {
            productService.delete(id);
        }
        return "redirect:/product/findAll";
    }
}
